﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static LightCAD.Three.Constants;

namespace LightCAD.Three
{
    public class RectAreaLightHelper : Line
    {
        public RectAreaLight light;
        public Color color;

        public RectAreaLightHelper(RectAreaLight light, Color color = null) :
            base(makeGeometry(), new LineBasicMaterial(new MaterialValues { fog = false }))
        {

            this.light = light;
            this.color = color; // optional hardwired color for the helper
            this.type = "RectAreaLightHelper";

            //
            var positions2 = new double[] { 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 };

            var geometry2 = new BufferGeometry();
            geometry2.setAttribute("position", new Float32BufferAttribute(positions2, 3));
            geometry2.computeBoundingSphere();

            this.add(new Mesh(geometry2, new MeshBasicMaterial(new MaterialValues { side = BackSide, fog = false })));

        }
        private static BufferGeometry makeGeometry()
        {
            var positions = new double[] { 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0 };

            var geometry = new BufferGeometry();
            geometry.setAttribute("position", new Float32BufferAttribute(positions, 3));
            geometry.computeBoundingSphere();
            return geometry;
        }
        public override void updateMatrixWorld(bool force = false)
        {
            this.scale.set(0.5 * this.light.width, 0.5 * this.light.height, 1);
            var lineMat = this.material as LineBasicMaterial;
            var mesh = this.children[0] as Mesh;
            if (this.color != null)
            {
                lineMat.color.set(this.color);
                mesh.material.color.set(this.color);
            }
            else
            {

                lineMat.color.copy(this.light.color).multiplyScalar(this.light.intensity);

                // prevent hue shift
                var c = lineMat.color;
                var max = JMath.max(c.r, c.g, c.b);
                if (max > 1) c.multiplyScalar(1 / max);

                mesh.material.color.copy(lineMat.color);

            }

            // ignore world scale on light
            this.matrixWorld.extractRotation(this.light.matrixWorld).scale(this.scale).copyPosition(this.light.matrixWorld);

            this.children[0].matrixWorld.copy(this.matrixWorld);

        }

        public void dispose()
        {
            this.geometry.dispose();
            this.material.dispose();
            (this.children[0] as Mesh).geometry.dispose();
            (this.children[0] as Mesh).material.dispose();
        }
    }
}
